import React, { Component } from 'react'
import '../App.css'
import Input from './Input';
// Different from "Header", use "state full class components"
export default class Meme extends Component{
    constructor(){
        super();
        this.state = {
            TopText : "",
            BottomText : "",
            TopTextNew:"",
            BottomTextNew:"",
            //Get a random image from the imgflip API
            RandomImage : "http://i.imgflip.com/1bij.jpg",
            MemeImages : [],
            showImage: false,
        }
        this.handleChange = this.handleChange.bind(this)
    }
    componentDidMount(){
        //HTTP request via Axios
        fetch("https://api.imgflip.com/get_memes")
        .then(response => response.json())
        .then(response => {
            const{memes} = response.data
            this.setState({
                MemeImages : memes
            })
        })

    }

    handleChange =(event) => {
        const {name,value} = event.target
        this.setState({
            [name] : value
        })
    }

    handleSubmit =(event) => {
        // Randomly selected images
        event.preventDefault();
        const num = Math.floor(Math.random() * this.state.MemeImages.length)
        const image = this.state.MemeImages[num].url

        this.setState({
            RandomImage : image,
            TopText: this.state.TopTextNew,
            BottomText: this.state.BottomTextNew,
            showImage:true,
        })
    }

    render(){
        // // Create reaction elements using JSX
        return(
            <div className="meme-body">
                {/* Text display */}
                <Input  handleChange={this.handleChange} handleSubmit={this.handleSubmit}/>
                <br/>
                {/* image display */}
                {this.state.showImage?(
                    <div className="img-div">
                        <h2><span className="toptext">{this.state.TopText}</span></h2>
                        <img src={this.state.RandomImage} onClick={this.handleSubmit} onError={this.handleSubmit} alt="meme"/>
                        <h2><span className="bottomtext">{this.state.BottomText}</span></h2>
                    </div>) : (
                    <div className="init_grey"></div>)  
                }
            </div>
        )
    }
}
